<?php
// 启动会话
session_start();

// 包含函数库
require_once 'functions.php';

// 检查管理员是否已登录
if (!is_admin_logged_in()) {
    header('Location: admin_login.html');
    exit;
}

// 处理密码重置
$reset_success = '';
$reset_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // 验证当前密码
    if (!check_admin_password($current_password)) {
        $reset_error = '当前密码错误';
    } elseif ($new_password !== $confirm_password) {
        $reset_error = '两次输入的新密码不一致';
    } elseif (strlen($new_password) < 6) {
        $reset_error = '新密码长度不能少于6位';
    } else {
        if (update_admin_password($new_password)) {
            $reset_success = '密码重置成功';
        } else {
            $reset_error = '密码重置失败';
        }
    }
}

// 处理系统设置
$settings_success = '';
$settings_error = '';
$settings_file = __DIR__ . '/settings.json';
$settings = [
    'footer_text' => '书信系统 - 保护您的私密通信',
    'icp_info' => ''
];

// 读取现有设置
if (file_exists($settings_file)) {
    $content = file_get_contents($settings_file);
    if ($content !== false) {
        $settings = json_decode($content, true) ?: $settings;
    }
}

// 处理设置提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    $new_settings = [
        'footer_text' => $_POST['footer_text'] ?? $settings['footer_text'],
        'icp_info' => $_POST['icp_info'] ?? $settings['icp_info']
    ];

    if (file_put_contents($settings_file, json_encode($new_settings, JSON_PRETTY_PRINT)) !== false) {
        $settings_success = '设置保存成功';
        $settings = $new_settings;
    } else {
        $settings_error = '设置保存失败，请检查文件权限';
    }
}

// 处理信件操作
$letter_success = '';
$letter_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 添加信件
    if (isset($_POST['add_letter'])) {
        $number = $_POST['number'];
        $content = $_POST['content'];
        if (add_letter($number, $content)) {
            $letter_success = '信件添加成功';
        } else {
            $letter_error = '信件添加失败';
        }
    }

    // 删除信件
    if (isset($_POST['delete_letter'])) {
        $number = $_POST['number'];
        if (delete_letter($number)) {
            $letter_success = '信件删除成功';
        } else {
            $letter_error = '信件删除失败';
        }
    }

    // 编辑信件
    if (isset($_POST['edit_letter'])) {
        $number = $_POST['number'];
        $content = $_POST['content'];
        if (update_letter($number, $content)) {
            $letter_success = '信件更新成功';
        } else {
            $letter_error = '信件更新失败';
        }
    }
}

// 获取所有信件
$letters = get_all_letters();

// 测试文件存储
function test_file_storage() {
    $storage_path = LETTERS_DIRECTORY;
    
    // 检查目录是否存在
    if (!file_exists($storage_path)) {
        return [
            'success' => false,
            'message' => '存储目录不存在: ' . $storage_path
        ];
    }
    
    // 检查目录是否可写
    if (!is_writable($storage_path)) {
        return [
            'success' => false,
            'message' => '存储目录不可写: ' . $storage_path
        ];
    }
    
    // 检查信件数量
    $files = glob($storage_path . '*.txt');
    $letter_count = count($files);
    
    return [
        'success' => true,
        'message' => '文件存储系统正常！当前信件数量: ' . $letter_count
    ];
}

$storage_test_result = test_file_storage();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书信系统 - 后台管理</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        .dashboard-container {
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
        }
        .card {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            padding: 20px;
            margin-bottom: 20px;
        }
        .card h2 {
            color: #5a4b3c;
            margin-bottom: 15px;
            font-weight: 600;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .btn-logout {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            float: right;
        }
        .btn-logout:hover {
            background-color: #c0392b;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        th {
            background-color: #f9f5e9;
            color: #5a4b3c;
        }
        .btn {
            display: inline-block;
            padding: 6px 12px;
            margin-right: 5px;
            border-radius: 4px;
            text-decoration: none;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-edit {
            background-color: #3498db;
            color: white;
        }
        .btn-delete {
            background-color: #e74c3c;
            color: white;
        }
        .btn-add {
            background-color: #2ecc71;
            color: white;
            margin-bottom: 15px;
        }
        .btn-test {
            background-color: #9b59b6;
            color: white;
            margin-right: 10px;
            margin-bottom: 10px;
            display: inline-block;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        .form-group input[type="text"],
        .form-group textarea,
        .form-group input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .form-group textarea {
            min-height: 150px;
            resize: vertical;
        }
        .success-message {
            color: #2ecc71;
            margin-bottom: 15px;
        }
        .error-message {
            color: #e74c3c;
            margin-bottom: 15px;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .tab {
            padding: 10px 15px;
            background-color: #f1ece1;
            border-right: 1px solid #e0d6c2;
            cursor: pointer;
        }
        .tab:last-child {
            border-right: none;
        }
        .tab.active {
            background-color: #a8927d;
            color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .test-links {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <div class="card">
            <h2>书信系统 - 后台管理</h2>
            <button class="btn-logout" onclick="location.href='admin_logout.php'">退出登录</button>
            <div style="clear: both;"></div>
        </div>

        <div class="tabs">
            <div class="tab active" onclick="switchTab('letters')">信件管理</div>
            <div class="tab" onclick="switchTab('add_letter')">添加信件</div>
            <div class="tab" onclick="switchTab('reset_password')">密码重置</div>
            <div class="tab" onclick="switchTab('settings')">系统设置</div>
            <div class="tab" onclick="switchTab('diagnostics')">测试诊断</div>
        </div>

        <!-- 信件管理 -->
        <div id="letters" class="tab-content active">
            <div class="card">
                <h2>信件列表</h2>
                <?php if (isset($letter_success)): ?>
                    <div class="success-message"><?php echo $letter_success; ?></div>
                <?php endif; ?>
                <?php if (isset($letter_error)): ?>
                    <div class="error-message"><?php echo $letter_error; ?></div>
                <?php endif; ?>
                <table>
                    <tr>
                        <th>数字号码</th>
                        <th>信件内容</th>
                        <th>创建时间</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                    <?php if (isset($letters) && count($letters) > 0): ?>
                        <?php foreach ($letters as $letter): ?>
                            <tr>
                                <td><?php echo $letter['number']; ?></td>
                                <td><?php echo substr($letter['content'], 0, 50); ?>...</td>
                                <td><?php echo $letter['created_at']; ?></td>
                                <td><?php echo $letter['updated_at']; ?></td>
                                <td>
                                    <button class="btn btn-edit" onclick="editLetter('<?php echo $letter['number']; ?>', '<?php echo addslashes($letter['content']); ?>')">编辑</button>
                                    <form action="admin_dashboard.php" method="post" style="display: inline;">
                                        <input type="hidden" name="number" value="<?php echo $letter['number']; ?>">
                                        <button type="submit" name="delete_letter" class="btn btn-delete" onclick="return confirm('确定要删除这封信件吗？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5">暂无信件数据</td>
                        </tr>
                    <?php endif; ?>
                </table>
            </div>
        </div>

        <!-- 添加信件 -->
        <div id="add_letter" class="tab-content">
            <div class="card">
                <h2>添加新信件</h2>
                <form action="admin_dashboard.php" method="post">
                    <div class="form-group">
                        <label for="number">数字号码:</label>
                        <input type="text" id="number" name="number" required>
                    </div>
                    <div class="form-group">
                        <label for="content">信件内容:</label>
                        <textarea id="content" name="content" required></textarea>
                    </div>
                    <button type="submit" name="add_letter" class="btn btn-add">添加信件</button>
                </form>
            </div>
        </div>

        <!-- 编辑信件模态框 -->
        <div id="editModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
            <div style="background-color: white; margin: 10% auto; padding: 20px; width: 80%; max-width: 600px; border-radius: 8px;">
                <h3>编辑信件</h3>
                <form id="editForm" action="admin_dashboard.php" method="post">
                    <input type="hidden" id="edit_number" name="number">
                    <div class="form-group">
                        <label for="edit_content">信件内容:</label>
                        <textarea id="edit_content" name="content" required></textarea>
                    </div>
                    <button type="submit" name="edit_letter" class="btn btn-add">更新信件</button>
                    <button type="button" onclick="document.getElementById('editModal').style.display='none'">取消</button>
                </form>
            </div>
        </div>

        <!-- 密码重置 -->
        <div id="reset_password" class="tab-content">
            <div class="card">
                <h2>密码重置</h2>
                <?php if (isset($reset_success)): ?>
                    <div class="success-message"><?php echo $reset_success; ?></div>
                <?php endif; ?>
                <?php if (isset($reset_error)): ?>
                    <div class="error-message"><?php echo $reset_error; ?></div>
                <?php endif; ?>
                <form action="admin_dashboard.php" method="post">
                    <div class="form-group">
                        <label for="current_password">当前密码:</label>
                        <input type="password" id="current_password" name="current_password" required>
                    </div>
                    <div class="form-group">
                        <label for="new_password">新密码:</label>
                        <input type="password" id="new_password" name="new_password" required>
                    </div>
                    <div class="form-group">
                        <label for="confirm_password">确认新密码:</label>
                        <input type="password" id="confirm_password" name="confirm_password" required>
                    </div>
                    <button type="submit" name="reset_password" class="btn btn-add">重置密码</button>
                </form>
            </div>
        </div>

        <!-- 系统设置 -->
        <div id="settings" class="tab-content">
            <div class="card">
                <h2>系统设置</h2>
                <?php if (isset($settings_success)): ?>
                    <div class="success-message"><?php echo $settings_success; ?></div>
                <?php endif; ?>
                <?php if (isset($settings_error)): ?>
                    <div class="error-message"><?php echo $settings_error; ?></div>
                <?php endif; ?>
                <form action="admin_dashboard.php" method="post">
                    <div class="form-group">
                        <label for="footer_text">底部文字内容:</label>
                        <input type="text" id="footer_text" name="footer_text" value="<?php echo htmlspecialchars($settings['footer_text']); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="icp_info">备案信息:</label>
                        <input type="text" id="icp_info" name="icp_info" value="<?php echo htmlspecialchars($settings['icp_info']); ?>">
                        <small>格式示例: 粤ICP备XXXXXXXX号</small>
                    </div>
                    <button type="submit" name="save_settings" class="btn btn-add">保存设置</button>
                </form>
            </div>
        </div>

        <!-- 测试诊断 -->
        <div id="diagnostics" class="tab-content">
            <div class="card">
                <h2>系统诊断</h2>
                <h3>文件存储测试</h3>
                <?php
                    $storage_test_result = test_file_storage();
                    if ($storage_test_result['success']) {
                        echo '<div class="success-message">' . $storage_test_result['message'] . '</div>';
                    } else {
                        echo '<div class="error-message">' . $storage_test_result['message'] . '</div>';
                    }
                ?>

                <h3>测试工具链接</h3>
                <div class="test-links">
                    <a href="test_redirect.html" class="btn btn-test" target="_blank">跳转功能测试</a>
                </div>

                <h3>服务器信息</h3>
                <p>PHP 版本: <?php echo phpversion(); ?></p>
                <p>服务器软件: <?php echo $_SERVER['SERVER_SOFTWARE']; ?></p>
                <p>当前时间: <?php echo date('Y-m-d H:i:s'); ?></p>
            </div>
        </div>
    </div>

    <script>
        // 切换标签
        function switchTab(tabId) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            // 移除所有标签的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            // 显示选中的标签内容
            document.getElementById(tabId).classList.add('active');
            // 激活选中的标签
            event.currentTarget.classList.add('active');
        }

        // 编辑信件
        function editLetter(number, content) {
            document.getElementById('edit_number').value = number;
            document.getElementById('edit_content').value = content;
            document.getElementById('editModal').style.display = 'block';
        }
    </script>
</body>
</html>